/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.yunyichina.provider.framework.annotation.validate;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * validate the @ValidateStringIn annotation
 *
 * @author jiangtch
 */
public class ValidateStringInHandler implements Handler {

    private static final Logger logger = LoggerFactory.getLogger(ValidateStringInHandler.class);

    public void validate(AnnotationValidable validatedObj, Field field)
            throws ValidateException {
        if (logger.isTraceEnabled()) {
            logger.trace(this.getClass().getName(), "validate()");
        }
        if (field.isAnnotationPresent(ValidateStringIn.class)) {
            checkStringIn(validatedObj, field);
        }
    }

    /**
     * validate the String value
     *
     * @param filter interceptor validated object
     * @param field  validated field or property
     * @throws ValidateException
     */
    private void checkStringIn(AnnotationValidable filter, Field field)
            throws ValidateException {
        if (logger.isTraceEnabled()) {
            logger.trace(this.getClass().getName(), "checkStringIn()");
        }
        ValidateStringIn annotation = field
                .getAnnotation(ValidateStringIn.class);
        String exceptValue = annotation.value();
        
        Object valueObject;
        try {
            valueObject = GetFiledValue.getField(filter, field.getName());
        } catch (Exception ex) {
            logger.error("字段：" + field.getName() + " 获取值发生异常->" + ex.getMessage(), ex);
            throw new ValidateException("字段：" + field.getName() + " 获取值发生异常->" + ex.getMessage(), ex);
        }
        
        if(valueObject==null){
            return;
        }
        
        String value=String.valueOf(valueObject);
        if (!"".equals(value) && value != null) {
            String[] validateValues = exceptValue.split(",");
            List<String> list = Arrays.asList(validateValues);
            if (!list.contains(value)) {
                logger.warn("字段：" + field.getName() + " 校验失败. 当前值为:" + value + ",值应该在以下范围内:" + Arrays.asList(validateValues));
                throw new ValidateException("字段：" + field.getName() + " 校验失败. 当前值为:" + value + ",值应该在以下范围内:" + Arrays.asList(validateValues));
            }
        }
    }

}
